//
//  AppDelegate.m
//  EarnBao
//
//  Created by xiaohui on 15/4/24.
//  Copyright (c) 2015年 杭州赚宝科技有限公司. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarController.h"
#import "EarnBao-API.h"
#import "AFNetworking.h"

//激活缓存
#import "RNCachingURLProtocol.h"
//唯一设备号
#import "OpenUDID.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

//激活缓存
- (void)activateCaches
{
    //将系统类注册成三方缓存类，激活缓存资源，使app在无网络连接的状态下自动使用缓存数据显示，提升用户体验！
    [NSURLProtocol registerClass:[RNCachingURLProtocol class]];
}

//查询沙盒
- (void)selectSandbox
{
    //1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    
    //2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
    
    //3.文件路径
    NSString *filepath = [docPath stringByAppendingPathComponent:@"app_daliy.plist"];
    
    //4.读取存放着当前使用的app相关数据信息的字典
    NSDictionary *dataDic = [NSDictionary dictionaryWithContentsOfFile:filepath];
    
    //判断沙盒中存放的当前使用的app相关数据信息的字典是否为空，若为空，则创建并传给服务器端，若不为空则返回。
    if (dataDic==nil) {
        
        //1.获得沙盒的根目录
        NSString *home = NSHomeDirectory();
        
        //2.获取Documents文件夹的路径
        NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
        
        //3.新建自定义文件的路径
        NSString *filepath = [docPath stringByAppendingPathComponent:@"app_daliy.plist"];
        
        //获取app当前时间
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yy-MM-dd HH:mm:ss"];
        NSDate *currentDate = [NSDate date];
        NSString *app_time = [formatter stringFromDate:currentDate];
        
        //获取app版本号
        NSDictionary *inforDic = [[NSBundle mainBundle] infoDictionary];
        NSString *app_version = inforDic[@"CFBundleShortVersionString"];
        
        //获取设备唯一标识
        NSString *device_token = [OpenUDID value];
        
        //获取系统版本号
        NSString *system_version = [[UIDevice currentDevice] systemVersion];
        
        //初始化将要上传到服务器的的数据字典
        NSDictionary *parameters = @{@"app_time":app_time, @"app_version": app_version, @"device_token":device_token, @"system_version":system_version};
        
        //4.将数据(字典)写入自定义文件
        [parameters writeToFile:filepath atomically:YES];
        
        
        //初始化请求对象
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        //GET请求(也可以用POST请求)
        [manager GET:kUpload parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            //NSLog(@"服务器返回的数据:%@",responseObject);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            //NSLog(@"服务器出错了！相关错误信息是:%@",error);
        }];
    }
    else {
        
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    TabBarController *tabBarC = [[TabBarController alloc] init];
    self.window.rootViewController = tabBarC;
    [NSThread sleepForTimeInterval:1.5];  //设置延迟启动
    [self.window makeKeyAndVisible];
    
    //查询沙盒中当前使用的app相关数据信息的字典是否为空
    [self selectSandbox];
    
    //激活缓存(包含app所有网络请求后的缓存资源，因使用了AFNetworking三方的原因，其内部封装有自动生成缓存的方法！这里只需要激活即可！)
    [self activateCaches];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
